package it.polito.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateAccessor;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import umls.geneus.core.data.Abstr;
import umls.geneus.server.data.Mapping;


public class GeneusDaoImpl implements GeneusDao{
	 private HibernateTemplate hTemplate;
	     public void setSessionFactory(SessionFactory sessionFactory) {
	         hTemplate = new HibernateTemplate(sessionFactory);
	        // hTemplate.setFlushMode(HibernateAccessor.FLUSH_COMMIT);
	         hTemplate.setFlushMode(HibernateAccessor.FLUSH_ALWAYS);
	     }

	@Override
	public List<String> getPubmedIdsFromKeyword(List<String> input) {
		
		return null;
	}

	@Override
	public String getAbstract(String id) throws DataNotFoundException {
	
		return hTemplate.get(Abstr.class, id).getText();
	}

	@Override
	public Mapping getMapping(final String id) {
	//	hTemplate.getSessionFactory().set(modifier_pattern ret_type_pattern type_pattern.id_pattern)
			return (Mapping) hTemplate.execute(new HibernateCallback<Mapping>() {
        public Mapping doInHibernate(Session session) throws HibernateException {
        	Mapping a = (Mapping) session.get(Mapping.class, id);
        	a.getMappings().size(); //maledettissimo hibernate, il suo lazy fetching mi ha obbligato a fare questo magheggio
        	return a;
        }
    });
	}

	@Override
	public void saveMapping(Mapping m) {
		hTemplate.saveOrUpdate(m);
	}

	@Override
	public void saveAbstract(String id, String abstr)
			throws DataAccessException {
		Abstr a = new Abstr(id,abstr);
		
		hTemplate.save(a);
	//	hTemplate.getSessionFactory().getCurrentSession().getTransaction().commit();
		//ctx.commit();
		
	//	hTemplate.getSessionFactory().openSession().createSQLQuery("commit").executeUpdate();
		
	}
	@Override
	public void saveAbstract(Abstr a)
			throws DataAccessException {
		hTemplate.save(a);
		
	}

}
